/**
 * @file ads1115_read.c
 * @brief 驱动板载ads1115获取adc四个通道的数据，需要注意的是引脚悬空有0.53V的电压，只有AIN接地之后才读到0V
 * @author CT Y
 * @version 1.0
 * @date 2023-05-21
 * 
 * @par 修改日志:
 * Date          Version Author  Description
 * 2023-05-21    1.0     CT Y    新增读取ads1115的内容，已经验证可用
 */
#include "main.h"
#include "ads1115_read.h"
#include "i2c.h"
angle_read_t angle_read;
//在手册Page26中规定，正值最大获取为0x7FFF,0为0x0000,负值最大为0x8000
const float voltageConv = 6.114 / 32768.0; //由手册得到的转换系数
unsigned char ADSwrite[6]; //向芯片发送的buffer，时序和寄存器见手册Page23-Page30
int16_t ads1115_reading[4];//获取到的4个通道原始值
float ads1115_voltage[4]; //转换到的4个通道电压值
void ads1115_read_task()
{
    osDelay(100);
    angle_read.adc1=0;
    angle_read.adc2=0;
    angle_read.adc3=0;
    angle_read.adc4=0;
    while (1)
    {

        for (int i = 0; i < 4; i++)
        {
            ADSwrite[0] = 0x01; //Register address pointer   01代表Config register

            switch (i)
            {
            case (0):
                ADSwrite[1] = 0xC1; //11000001  D[14:12]为100，即 AINP = AIN0 and AINN = GND
                break;
            case (1):
                ADSwrite[1] = 0xD1; //11010001 之后以此类推
                break;
            case (2):
                ADSwrite[1] = 0xE1;
                break;
            case (3):
                ADSwrite[1] = 0xF1;
                break;
            }

            ADSwrite[2] = 0x83; //10000011 LSB

            HAL_I2C_Master_Transmit(&hi2c2, ADS1115_ADDRESS << 1, ADSwrite, 3, 100);
            ADSwrite[0] = 0x00;
            HAL_I2C_Master_Transmit(&hi2c2, ADS1115_ADDRESS << 1, ADSwrite, 1, 100);
            osDelay(10);

            HAL_I2C_Master_Receive(&hi2c2, ADS1115_ADDRESS << 1, ADSwrite, 2, 100);
            ads1115_reading[i] = (ADSwrite[0] << 8 | ADSwrite[1]);
            if (ads1115_reading[i] < 0) //强行取正
            {
                ads1115_reading[i] = 0;
            }

            ads1115_voltage[i] = ads1115_reading[i] * voltageConv;
        }

        angle_read.adc1 = 1.0*ads1115_reading[0];
        angle_read.adc2 = 1.0*ads1115_reading[1];
        angle_read.adc3 = 1.0*ads1115_reading[2];
        angle_read.adc4 = 1.0*ads1115_reading[3];
        osDelay(10);
    }
}